﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Jayden.Dll.Web.HtmlControls;
using Jayden.Dll.Web.Json;
using System.IO;
using System.Globalization;

namespace Jayden.Dll.Web.Controls.OnlineOS
{
	public class OnlineOSHtml : Html
	{

		protected JsonValue ListDirectory(string path, bool directoryOnly = false, bool countChildrenDirectory = false)
		{
			CultureInfo culture = new CultureInfo("fr-BE");
			string searchPattern = "*";
			string[] files = Directory.GetFiles(path, searchPattern, SearchOption.TopDirectoryOnly);
			string[] directories = Directory.GetDirectories(path);

			JsonArray children = new JsonArray();
			foreach (string directory in directories)
			{
				DirectoryInfo info = new DirectoryInfo(directory);
				string name = Path.GetFileName(directory);
				JsonObject obj = new JsonObject();
				obj.Add("name", name);
				obj.Add("directory", true);
				obj.Add("icon", "/Images/Icons/OOS/Folder.png");
				obj.Add("type", "Dossier de fichiers");
				obj.Add("modified", info.LastWriteTime.ToString("d/MM/yyyy HH:mm"));
				if (countChildrenDirectory)
				{
					try
					{
						string[] childrenDirectories = Directory.GetDirectories(directory);
						int childrens = childrenDirectories.Length;
						obj.Add("hasChildrenDirectory", childrens > 0);
					}
					catch
					{
						obj.Add("accessDenied", true);
					}
				}
				children.Add(obj);
			}
			if (!directoryOnly)
			{
				foreach (string file in files)
				{
					FileInfo info = new FileInfo(file);
					string name = Path.GetFileName(file);
					JsonObject obj = new JsonObject();
					obj.Add("name", name);
					obj.Add("modified", info.LastWriteTime.ToString("d/MM/yyyy HH:mm"));
					obj.Add("icon", "/Images/html5-icon.png");
					obj.Add("size", Math.Round(info.Length / 1024.0).ToString("###,###,##0", culture) + " Ko");
					children.Add(obj);
				}
			}

			JsonObject result = new JsonObject();
			result.Add("children", children);

			return result;
		}

		public override void ProcessJsonRequest(HttpHandlerContext context)
		{
			base.ProcessJsonRequest(context);
			string command = context.Request["command"];
			if (!string.IsNullOrWhiteSpace(command))
			{
				string path = null;
				bool directoryOnly = false;
				bool countChildrenDirectory = false;
				long requestId = long.Parse(context.Request["requestId"]);

				switch (command)
				{
					case "listDirectory":
						path = context.Request["path"];
						directoryOnly = (context.Request["directoryOnly"] == "true");
						countChildrenDirectory = (context.Request["countChildrenDirectory"] == "true");
						context.Json.Add("directory", ListDirectory(path, directoryOnly, countChildrenDirectory));
						break;
				}

				context.Json.Add("requestId", requestId);
				context.Json.Add("command", command);
			}
		}
	}
}
